/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.googlecode.jsimplemarket.wicket.pages;

import com.googlecode.jsimplemarket.model.Absenta;
import com.googlecode.jsimplemarket.model.Creanta;
import com.googlecode.jsimplemarket.model.DetaliuPiata;
import com.googlecode.jsimplemarket.model.Firma;
import com.googlecode.jsimplemarket.model.Inchiriere;
import com.googlecode.jsimplemarket.model.NStareSpatiuComercial;
import com.googlecode.jsimplemarket.model.ObservatieSpatiuComercial;
import com.googlecode.jsimplemarket.model.Plata;
import com.googlecode.jsimplemarket.model.RaportIncasari;
import com.googlecode.jsimplemarket.model.SpatiuComercial;
import com.googlecode.jsimplemarket.model.Taxa;
import com.googlecode.jsimplemarket.model.TotalIncasari;
import com.googlecode.jsimplemarket.model.Utilizator;
import com.googlecode.jsimplemarket.model.ZZZ;
import com.googlecode.jsimplemarket.service.AbsentaService;
import com.googlecode.jsimplemarket.service.GenericService;
import com.googlecode.jsimplemarket.service.InchiriereService;
import com.googlecode.jsimplemarket.service.SpatiuComercialService;
import com.googlecode.jsimplemarket.service.StareSpatiuComercialService;
import com.googlecode.jsimplemarket.service.TaxaService;
import com.googlecode.jsimplemarket.service.ObservatieSpatiuComercialService;
import com.googlecode.jsimplemarket.service.ZZZService;
import com.googlecode.jsimplemarket.wicket.SecuredWebSession;

//import com.googlecode.jsimplemarket.wicket.zzz.ZZZAddPage;
import com.googlecode.jsimplemarket.wicket.zzz.ZZZListPage;




//import com.googlecode.jsimplemarket.wicket.pages.TarabaViewPage.PlataRapidaListView;
import org.wicketstuff.security.components.SecureWebPage;

import java.math.BigDecimal;
import java.text.DateFormat;
import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;
import java.util.Locale;

import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.ajax.markup.html.form.AjaxSubmitLink;
import org.apache.wicket.behavior.AttributeAppender;
import org.apache.wicket.feedback.ContainerFeedbackMessageFilter;
import org.apache.wicket.markup.html.WebMarkupContainer;
import org.apache.wicket.markup.html.WebPage;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.form.Form;
//import org.apache.wicket.markup.html.form.SubmitLink;
import org.apache.wicket.markup.html.form.TextField;
import org.apache.wicket.markup.html.link.Link;
import org.apache.wicket.markup.html.list.ListItem;
import org.apache.wicket.markup.html.list.ListView;
import org.apache.wicket.markup.html.panel.FeedbackPanel;
//import org.apache.wicket.model.CompoundPropertyModel;
import org.apache.wicket.model.Model;
//import org.apache.wicket.model.PropertyModel;
import org.apache.wicket.spring.injection.annot.SpringBean;
import org.apache.wicket.validation.validator.StringValidator;
//import org.apache.wicket.validation.validator.PatternValidator;
import org.springframework.security.core.GrantedAuthority;

/**
 *
 * @author Alexandru.Codescu
 */
public class PiataViewPage extends SecureWebPage {
    @SpringBean(name = "inchiriereService")
    private InchiriereService inchiriereService;
    @SpringBean(name = "taxaService")
    private TaxaService taxaService;
    @SpringBean(name = "genericService")
    private GenericService<ZZZ> serviceZzz;
    @SpringBean(name = "genericService")
    private GenericService<SpatiuComercial> spatiuComercialService;
    @SpringBean(name = "genericService")
    private GenericService<Plata> plataService;
    @SpringBean(name = "genericService")
    private GenericService<Creanta> creantaService;
    @SpringBean(name = "genericService")
    private GenericService<Inchiriere> serviceInchiriere;
    @SpringBean(name = "genericService")
    private GenericService<Firma> serviceFirma;
    @SpringBean(name = "genericService")
    private GenericService<Absenta> serviceAbsenta;
    @SpringBean(name = "absentaService")
    private AbsentaService absentaService;
    @SpringBean(name = "stareSpatiuComercialService")
    private StareSpatiuComercialService stareSpatiuComercialService;
    @SpringBean(name = "spatiuComercialService")
    private SpatiuComercialService scService;
    @SpringBean(name = "genericService")
    private GenericService<ObservatieSpatiuComercial> ServiceObservatieSpatiuComercial;
    @SpringBean(name = "observatieSpatiuComercialService")
    private ObservatieSpatiuComercialService observatieSpatiuComercialService;
	
	@SpringBean(name = "zzzService")
    private ZZZService zzzService;    
   
    private Date today = new Date(); // data curenta
    private Date dateS = addDays(today, 0); // data azi resetata la miezul noptii
    private Date dateF = addDays(today, 1); // data maine cu data curenta + o zi
    
    private Locale locale = new Locale("ro","RO");
    private NumberFormat fmt = NumberFormat.getCurrencyInstance(locale);
    private Long Totalabsente;
    private String stareSpatiu;
    private ObservatieSpatiuComercial observatiePiata;
    private ZZZ zzz;
	
	public static Date addDays(Date date, int days) {
        GregorianCalendar cal = new GregorianCalendar();
        cal.setTime(date);
        cal.add(Calendar.DATE, days);
//        cal.set(Calendar.HOUR_OF_DAY, 0); //doar cand se lucreaza cu 24h format
        cal.set(Calendar.HOUR, 0);
        cal.set(Calendar.MINUTE, 0);
        cal.set(Calendar.SECOND, 0);
        cal.set(Calendar.AM_PM, Calendar.AM);
        cal.set(Calendar.MILLISECOND, 0);
                 
        return cal.getTime();
    }
    
    private Link createNavigationLink(String id, final Class<? extends WebPage> pageClass, String... roles) {
        Link link = new Link(id) {
            @Override
            public void onClick() {
                setResponsePage(pageClass);
            }
        };
        boolean visible = false;
        for (GrantedAuthority authority : getUtilizator().getAuthorities()) {
            for (String role : roles) {
                if (authority.getAuthority().equalsIgnoreCase(role)) {
                    visible = true;
                    break;
                }
            }
            if (visible) {
                break;
            }
        }

        link.setVisible(visible);
        return link;
    }

    protected Utilizator getUtilizator() {
        return ((SecuredWebSession) getSession()).getUserDetail().getUtilizator();
    }

    protected String getUsername() {
        return ((SecuredWebSession) getSession()).getUserDetail().getUsername();
    }
    
    public String printStandardDate(Date data) {
		return new SimpleDateFormat("dd.MM.yyyy HH:mm").format(data);
	}

    @SuppressWarnings("serial")
	public PiataViewPage() {
    	Totalabsente = absentaService.AbsenteByDay(new Date()).longValue();
    	final BigDecimal soldinit = zzzService.queryZZZByMagazinSum(dateS, dateF);
    	final BigDecimal sold = soldinit==null ? BigDecimal.ZERO : soldinit;
        Link lkLogout = new Link("logoutLink") {
            @Override
            public void onClick() {
                getSession().invalidateNow();
                setResponsePage(LoginPage.class);
            }
        };
        Label lblNumeUtilizator = new Label("username", getUsername());
        Link linkLogo = createNavigationLink("logoLink", PiataViewPage.class, "ROLE_ADMIN");
        Link linkDash = createNavigationLink("dashboardLink", AdminPage.class, "ROLE_ADMIN");
        add(linkLogo, linkDash, lkLogout, lblNumeUtilizator);
        List<List<DetaliuPiata>> spatii = scService.queryStatisticiSpatiuComercial();
        add(new RandView("rand", spatii));
        add(new Label("data", new SimpleDateFormat("dd-MM-yyyy").format(new Date())));

        Link detailLink = new Link("details") {
            @Override
            public void onClick() {
                setResponsePage(new RaportTarabePage());
            }
        };
        
        Link detailLinkAA = new Link("detailsAA") {
            @Override
            public void onClick() {
                setResponsePage(new RaportTarabePageAA());
            }
        };
        
        Link detailLinkAbs = new Link("detailsAbs") {
            @Override
            public void onClick() {
                setResponsePage(new RaportAbsentePage());
            }
        };
        
        final List<TotalIncasari> ttz = inchiriereService.queryTotalIncasariByData(new Date());
        BigDecimal sumTTZ = ttz==null ? BigDecimal.ZERO : ttz.get(0).getValoareTotala();
        
        final List<Object[]> tat = inchiriereService.queryTotalIncasariByDataPlata(new Date());
        BigDecimal sumTAT = tat==null ? BigDecimal.ZERO : new BigDecimal((tat.get(0))[0].toString());
                
        BigDecimal sumAzi = sumTTZ.add(sumTAT.add(sold));
        
//        Label totalTaxeZilnice = new Label("totalTaxeZilnice", fmt.format(sumTTZ));
//        Label totalAlteTaxe = new Label("totalAlteTaxe", fmt.format(sumTAT));
//        Label totalZzz = new Label("totalZzz",  fmt.format(sold));
//        Label totalAzi = new Label("totalAzi", fmt.format(sumAzi));
        
        Label totalTaxeZilnice = new Label("totalTaxeZilnice", sumTTZ);
        Label totalAlteTaxe = new Label("totalAlteTaxe", sumTAT);
        Label totalZzz = new Label("totalZzz",  sold);
        Label totalAzi = new Label("totalAzi", sumAzi);
        
        add(totalTaxeZilnice,totalAlteTaxe,totalZzz,totalAzi);
        
        add(detailLink,detailLinkAA,detailLinkAbs);
        
        add(new RaportIncasariView("raport", inchiriereService.queryIncasariByData(new Date())));
        final TotalIncasariView totalView = new TotalIncasariView("raportTotal", inchiriereService.queryTotalIncasariByData(new Date()));
        add(new Label("totalAbsente", Totalabsente)); 
        add(totalView);
        ExtraPlatiView extraView = new ExtraPlatiView("raportExtra", inchiriereService.queryIncasariByDataPlata(new Date()));
        AbsenteView absenteView = new AbsenteView("absenteView", absentaService.queryByDay(new Date()));
        TotalIncasariExtraView totalExtraView = new TotalIncasariExtraView("raportTotalExtra", inchiriereService.queryTotalIncasariByDataPlata(new Date()));
        add(totalExtraView,extraView, absenteView);        
//        final CommentsView commentsView = new CommentsView("lastComments",
//        		observatieSpatiuComercialService.queryObservatiiByDay(new Date()) );
//        final WebMarkupContainer wmcComments = new WebMarkupContainer("wmcComments");
//        wmcComments.setOutputMarkupId(true);
//        wmcComments.setOutputMarkupPlaceholderTag(true);
//        wmcComments.add(commentsView);
//        add(wmcComments);
       
//        Form formC = new Form("formC");
//        final TextField<String> tfObservatie = new TextField<String>("observatie",new Model<String>(""));
//       
//        tfObservatie.setRequired(true);
//        tfObservatie.add(StringValidator.minimumLength(4));
//        tfObservatie.setOutputMarkupId(true);        
        
//        final FeedbackPanel feedbackPanelC = new FeedbackPanel("feedbackComments");
//        feedbackPanelC.setOutputMarkupId(true);
        
//        formC.add(tfObservatie,feedbackPanelC);
//        feedbackPanelC.setFilter(new ContainerFeedbackMessageFilter(formC));
        
//        formC.add(new AjaxSubmitLink("submitC") {
//
//            @Override
//            public void onSubmit(AjaxRequestTarget target, Form formC) {
//                super.onSubmit(target, formC);
//                tfObservatie.processInput();
//                observatiePiata = new ObservatieSpatiuComercial();
//                observatiePiata.setUtilizator(getUtilizator());
//                observatiePiata.setObservatie(tfObservatie.getValue());
//            	ServiceObservatieSpatiuComercial.insert(observatiePiata);
//                commentsView.setList(observatieSpatiuComercialService.queryObservatiiByDay(new Date()));
//                commentsView.modelChanged();
//                tfObservatie.setModel(new Model<String>(""));
//                tfObservatie.modelChanged();
//                target.add(wmcComments,tfObservatie,feedbackPanelC);
//                            
//            }
//            @Override
//            public void onError(AjaxRequestTarget target, Form formC) {
//                super.onError(target, formC);
////                labelC.setVisible(true);
//                target.add(feedbackPanelC);
//                            
//            }
//            
//            
//        });
//        add(formC);
		
        final WebMarkupContainer wmcZzz = new WebMarkupContainer("wmcZzz");
        wmcZzz.setOutputMarkupId(true);
        wmcZzz.setOutputMarkupPlaceholderTag(true);
        
		final ZZZView zzzView = new ZZZView("bonuriAzi", zzzService.queryZZZByMagazinAll(dateS, dateF));
        
        final Label lblVandAzi = new Label("vanzariAzi", sold==null ? "0,00 LEI" : fmt.format(sold));
 
        wmcZzz.add(zzzView,lblVandAzi);
        add(wmcZzz);

        Link detailLinkAI = new Link("detailsAlteIncasari") {
            @Override
            public void onClick() {
                setResponsePage(new ZZZListPage());
            }
        };
        add(detailLinkAI);
        
        Form<?> formAI = new Form<Void>("formAI"); //alte incasari din ZZZ
        
        final TextField<String> tfDenumire = new TextField<String>("denumire", new Model<String>(""));
        final TextField<String> tfValoare = new TextField<String>("valoareTotala", new Model<String>(""));
        //tfValoare.add(new PatternValidator("[0-9_-]+"));
        
        tfValoare.setRequired(true);
    	tfValoare.setOutputMarkupId(true);
        
    	tfDenumire.setRequired(true);
    	tfDenumire.setOutputMarkupId(true);
    	
    	final FeedbackPanel feedbackPanelAI = new FeedbackPanel("feedbackAI");
    	feedbackPanelAI.setOutputMarkupId(true);
    	//feedbackPanelAI.setOutputMarkupPlaceholderTag(true);
    	//feedbackPanelAI.setVisible(false);
    	
    	formAI.add(tfDenumire,tfValoare,feedbackPanelAI);
    	feedbackPanelAI.setFilter(new ContainerFeedbackMessageFilter(formAI));
    	       
    	formAI.add(new AjaxSubmitLink("submitAI") {

            @Override
            public void onSubmit(AjaxRequestTarget target, Form formAI) {
                super.onSubmit(target, formAI);
                tfDenumire.processInput();
                tfValoare.processInput();
                
                try {
                    BigDecimal valoareSold = new BigDecimal(tfValoare.getValue());
                    zzz = new ZZZ();
	                zzz.setDataAdaugarii(new Date());
	                zzz.setUtilizator(getUtilizator());
	                zzz.setDenumire(tfDenumire.getValue());
	                zzz.setValoareTotala(valoareSold);
	            	serviceZzz.insert(zzz);
	            	
	            	zzzView.setList(zzzService.queryZZZByMagazinAll(dateS, dateF));
	            	zzzView.modelChanged();        	
	            	lblVandAzi.setDefaultModelObject(fmt.format(zzzService.queryZZZByMagazinSum(dateS, dateF)));
	            	lblVandAzi.modelChanged();
	            	
	            	tfDenumire.setModel(new Model<String>(""));
	            	tfDenumire.modelChanged();
	            	tfValoare.setModel(new Model<String>(""));
	            	tfValoare.modelChanged();
	            	feedbackPanelAI.setVisible(true);
	            	info("Adaugare reusita!");
	                target.add(wmcZzz,tfDenumire,tfValoare,feedbackPanelAI);
                    
                    
                } catch(NumberFormatException e) {
                    //throw new RuntimeException("Not a valid number");
                	error("Nu ati introdus un numar valid! " + e.getMessage());
                	tfDenumire.setModel(new Model<String>(""));
	            	tfDenumire.modelChanged();
	            	tfValoare.setModel(new Model<String>(""));
	            	tfValoare.modelChanged();
	            	//feedbackPanelAI.setVisible(true);
	            	target.add(tfDenumire,tfValoare,feedbackPanelAI);
                    
                }
                
                
                            
            }
            
            @Override
            public void onError(AjaxRequestTarget target, Form formAI) {
                super.onError(target, formAI);
                //labelC.setVisible(true);
                target.add(feedbackPanelAI);
                            
            }
            
        });
        add(formAI);

    }

    class RandView extends ListView<List<DetaliuPiata>> {

        public RandView(String id, List<List<DetaliuPiata>> randuri) {
            super(id, randuri);
        }

        @Override
        protected void populateItem(ListItem<List<DetaliuPiata>> li) {
            li.add(new SpatiuView("spatiu", li.getModelObject()));
        }
    }

    class SpatiuView extends ListView<DetaliuPiata> {

        private List<Taxa> taxe;
        private List<Taxa> taxe25;
       
        public SpatiuView(String id, List<DetaliuPiata> spatii) {
            super(id, spatii);
            taxe = taxaService.queryTaxePlataRapida015();
            taxe25 = taxaService.queryTaxePlataRapida25();
        }

        @Override
        protected void populateItem(ListItem<DetaliuPiata> li) {
            final DetaliuPiata spatiuComercial = li.getModelObject();

            WebMarkupContainer detailLink = new WebMarkupContainer("detailLink");
            detailLink.add(new Label("codLabel", spatiuComercial.getCod()));
            
//            stareSpatiu = spatiuComercial.getCssClass();
            stareSpatiu = (spatiuComercial.getTcss()==null ? "btn-default" : spatiuComercial.getTcss());
            
            detailLink.add(new AttributeAppender("class", " " + stareSpatiu));
            detailLink.add(new AttributeAppender("data-target", "#M" + spatiuComercial.getId()));

            li.add(detailLink);

            WebMarkupContainer divModal = new WebMarkupContainer("divModal");
            divModal.add(new AttributeAppender("id", "M" + spatiuComercial.getId()));

            Link detailProd = new Link("detailProd") {
                @Override
                public void onClick() {
                    setResponsePage(new TarabaViewPage(spatiuComercial.getId()));
                }
            };
            divModal.add(new Label("codTaraba", spatiuComercial.getCod()));
            
            String statusTaraba = spatiuComercial.getStare();
            
            String denumireOcupant = statusTaraba==null ? "---" : spatiuComercial.getFirma();
            final Label lblOcupant = new Label("lblOcupant", denumireOcupant == null ? "---" : denumireOcupant);
            
            //String statusTaraba = spatiuComercial.getStare();
            final Label lblStatus = new Label("statusTaraba", statusTaraba==null ? "Disponibil" : statusTaraba);
            
            String textAbsenta = "Luna curenta: " + (spatiuComercial.getAbsente() == null ? "0" : spatiuComercial.getAbsente());
            Label lblAbsenta = new Label("lblAbsenta", textAbsenta);
            if ((spatiuComercial.getAbsente() != null) && (spatiuComercial.getAbsente().longValue() >= 5L))  {
            	lblAbsenta.add(new AttributeAppender("class", "text-danger"));
            } else {
            	lblAbsenta.add(new AttributeAppender("class", "text-success"));
            }
            
//            GenericRestriction resTaxa = new GenericRestriction(new GenericProperty("taxa").setReference(new GenericProperty("id")), 2);
            
            
            PlataRapidaListView plataRapidaView = new PlataRapidaListView("plataRapida", taxe, spatiuComercial.getId());
            PlataRapidaListView plataRapidaView25 = new PlataRapidaListView("plataRapida25", taxe25, spatiuComercial.getId());
            
            Link btnAbsenta = new Link("btnAbsenta") {

                @Override
                public void onClick() {
                    SpatiuComercial spatiu = spatiuComercialService.getById(SpatiuComercial.class, spatiuComercial.getId());
                    Object[] sc = inchiriereService.queryFirmaByTaraba(spatiuComercial.getId(), new Date());
                    Firma firma = null;
                    if (sc != null) {
                        firma = serviceFirma.getById(Firma.class, (Long) sc[3]);
                        Absenta absenta = new Absenta();
                        absenta.setFirma(firma);
                        absenta.setSpatiuComercial(spatiu);
                        absenta.setDataAbsenta(new Date());
                        serviceAbsenta.insert(absenta);
                        setResponsePage(PiataViewPage.class);

                    }
                }
                
            };
           
            //Label lblAbsente = new Label("lblAbsente", "Luna curenta: 3");
            
            divModal.add(lblOcupant, lblStatus, plataRapidaView, btnAbsenta,
            		lblAbsenta, plataRapidaView25, detailProd);
            li.add(divModal);

        }
    }
   

    class ObservatiiView extends ListView<ObservatieSpatiuComercial> {

        public ObservatiiView(String id, List<ObservatieSpatiuComercial> observatiiSpatii) {
            super(id, observatiiSpatii);
        }

        @Override
        protected void populateItem(ListItem<ObservatieSpatiuComercial> li) {
            ObservatieSpatiuComercial observatie = li.getModelObject();
            li.add(new Label("observatie", observatie.getObservatie()));
        }
    }

    class RandSpatiiComercialeView extends ListView<SpatiuComercial> {

        public RandSpatiiComercialeView(String id, List<SpatiuComercial> spatiiComerciale) {
            super(id, spatiiComerciale);
        }

        @Override
        protected void populateItem(ListItem<SpatiuComercial> li) {
            SpatiuComercial spatiuComercial = li.getModelObject();
            li.add(new Label("cod", spatiuComercial.getCod()));
            li.add(new Label("stare", spatiuComercial.getStareSpatiuComercial().getDenumire()));
            li.add(new Label("tip", spatiuComercial.getTipSpatiuComercial().getDenumire()));
            li.add(new ObservatiiView("observatii", spatiuComercial.getObservatii()));
        }
    }

    class RaportIncasariView extends ListView<RaportIncasari> {

        public RaportIncasariView(String id, List<RaportIncasari> list) {
            super(id, list);
        }

        @Override
        protected void populateItem(ListItem<RaportIncasari> li) {
            int index = li.getIndex() + 1;
            RaportIncasari raport = li.getModelObject();

            Label lblIndex = new Label("index", index);
            Label lblDenumireTaxa = new Label("denumireTaxa", raport.getDenumireTaxa());
            Label lblNrSpatii = new Label("nrSpatii", raport.getNrSpatii());
            Label lblValoareTaxa = new Label("valoareTaxa", raport.getValoareTaxa());
            Label lblValoareTotala = new Label("valoareTotala", fmt.format(raport.getValoareTotala()));

            li.add(lblIndex, lblDenumireTaxa, lblNrSpatii, lblValoareTaxa, lblValoareTotala);
        }
    }

    class TotalIncasariView extends ListView<TotalIncasari> {

        public TotalIncasariView(String id, List<TotalIncasari> list) {
            super(id, list);
        }

        @Override
        protected void populateItem(ListItem<TotalIncasari> li) {
            TotalIncasari raport = li.getModelObject();
            Label lblToatalTarabe = new Label("totalTarabe", raport.getTotalSpatii());
            Label lblValoareTotala = new Label("valTotala", raport.getValoareTotala()==null ? "0" : fmt.format(raport.getValoareTotala()));
            li.add(lblValoareTotala,lblToatalTarabe);
        }
    }
    
    private class TotalIncasariExtraView extends ListView<Object[]> {

        public TotalIncasariExtraView(String id, List<Object[]> data) {
            super(id, data);
        }

        @Override
        protected void populateItem(ListItem<Object[]> li) {
            Object[] object = li.getModelObject();
            Label lblToatalTarabe = new Label("totalTarabeExtra", object==null ? "0" : object[1].toString());
            Label lblValoareTotala = new Label("valTotalaExtra", object[0]==null ? "0" : fmt.format(object[0]));
            li.add(lblValoareTotala,lblToatalTarabe);
        }
    }
    
    private class CommentsView extends ListView<Object[]> {

        public CommentsView(String id, List<Object[]> data) {
            super(id, data);
        }

        @Override
        protected void populateItem(ListItem<Object[]> li) {
            Object[] object = li.getModelObject();
            Label lblUser = new Label("createdBy", object==null ? "0" : object[2].toString());
            Label lblDate = new Label("createdDate", printStandardDate((Date) object[0]));
            Label lblComment = new Label("observatie", object==null ? "0" : object[1].toString());
            li.add(lblUser,lblDate,lblComment);
        }
    }
    
    private class ExtraPlatiView extends ListView<Object[]> {

        public ExtraPlatiView(String id, List<Object[]> data) {
            super(id, data);
        }

        @Override
        protected void populateItem(ListItem<Object[]> li) {
            Object[] object = li.getModelObject();
            int index;
            if (object==null){
            	index = 0;
            } else {
            	index = li.getIndex() + 1;
            }
            
            li.add(new Label("index", object==null ? "-" : index));
            li.add(new Label("denumireTaxa", object==null ? "-" : object[0].toString()));
            li.add(new Label("nrSpatii", object==null ? "-" : object[2].toString()));
            li.add(new Label("valoareTaxa", object==null ? "-" : object[1].toString()));
            //li.add(new Label("valoareTotala", object[3].toString()));
            li.add(new Label("valoareTotala", object == null ? "0" : fmt.format(object[3])));
        }
    }
	
	private class ZZZView extends ListView<Object[]> {

        public ZZZView(String id, List<Object[]> data) {
            super(id, data);
        }

        @Override
        protected void populateItem(ListItem<Object[]> li) {
            Object[] object = li.getModelObject();
            li.add(new Label("denumire", object==null ? "-" : object[0].toString()));
            li.add(new Label("dataAdaugarii", object==null ? "-" : DateFormat.getDateInstance(DateFormat.SHORT, locale).format(object[1])));
            li.add(new Label("valoareTotala", object==null ? "-" : fmt.format(object[2])));
        }
    }
    
    private class AbsenteView extends ListView<Object[]> {

        public AbsenteView(String id, List<Object[]> data) {
            super(id, data);
        }

        @Override
        protected void populateItem(ListItem<Object[]> li) {
            final Object[] object = li.getModelObject();
            int index;
            if (object==null){
            	index = 0;
            } else {
            	index = li.getIndex() + 1;
            }
            
            li.add(new Label("index", object==null ? "-" : index));
            //li.add(new Label("taraba", object==null ? "-" : object[0].toString()));
            
            Link lnkTaraba = new Link("lnkTaraba") {
                @Override
                public void onClick() {
                    setResponsePage(new TarabaViewPage((Long) object[2]));
                }
            };
            
            String lblText = object[0].toString();
            if (((Long) object[6])>1) {
            	lblText = object[0].toString() + " (" + object[6] + ")";
            }
            
            lnkTaraba.add(new Label("taraba", object==null ? "-" : lblText));
            li.add(lnkTaraba);
            
            li.add(new Label("ocupant", object==null ? "-" : object[1].toString()));
            li.add(new Label("incasare", object[5]==null ? "-" : object[5].toString()));
            
        }
    }
    
    
    
    public class PlataRapidaListView extends ListView<Taxa> {

        private Long idSpatiu;
        private Firma firma; //existenta pt select

        public PlataRapidaListView(String id, List<Taxa> list, Long idSpatiu) {
            super(id, list);
            this.idSpatiu = idSpatiu;

        }

        private Date getDataSfarsit(Date dataInceput, int interval) {
            GregorianCalendar gregorianCalendar = new GregorianCalendar();
            gregorianCalendar.setTime(dataInceput);
            gregorianCalendar.add(GregorianCalendar.DATE, interval);

            return gregorianCalendar.getTime();
        }

        @Override
        protected void populateItem(ListItem<Taxa> li) {
            final Taxa taxa = li.getModelObject();
            Link lkPlataRapida = new Link("lkPlataRapida") {

                @Override
                public void onClick() {
                    SpatiuComercial spatiuComercial = spatiuComercialService.getById(SpatiuComercial.class, idSpatiu);
                    Inchiriere inchiriere = new Inchiriere();

                    if ((taxa.getValoare().toString().equals("0.00") || taxa.getValoare().toString().equals("15.00"))) {

                        Object[] sc = inchiriereService.queryFirmaByTaraba((Long) idSpatiu, new Date());
                        if (sc != null) {
                            firma = serviceFirma.getById(Firma.class, (Long) sc[3]);
                            inchiriere.setFirma(firma);
                        }

                    }
                    
                    // Determinare noua stare a spatiului comercial
                    NStareSpatiuComercial stareNoua = null;
                    if (taxa.getValoare().toString().equals("0.00")) {
                        stareNoua = stareSpatiuComercialService.findByCod("AI");
                    } else if (taxa.getValoare().toString().equals("15.00")) {
                        stareNoua = stareSpatiuComercialService.findByCod("3");
                    } else if (taxa.getValoare().toString().equals("25.00")) {
                        stareNoua = stareSpatiuComercialService.findByCod("2");
                    }
                    spatiuComercial.setStareSpatiuComercial(stareNoua);
                    spatiuComercialService.update(spatiuComercial);

                    inchiriere.setDataInceput(new Date());
                    inchiriere.setDataSfarsit(new Date());
                    inchiriere.setSpatiuComercial(spatiuComercial);
                    inchiriere.setTaxe(new ArrayList<Taxa>());
                    inchiriere.getTaxe().add(taxa);
                    serviceInchiriere.insert(inchiriere);

                    Creanta creanta = new Creanta();
                    creanta.setDataInceput(new Date());
                    creanta.setDataSfarsit(getDataSfarsit(creanta.getDataInceput(), 1));
                    creanta.setTaxa(taxa);
                    creanta.setValoare(taxa.getValoare());
                    creanta.setValoareReziduala(BigDecimal.ZERO);
                    creanta.setPlati(new ArrayList<Plata>());
                    creanta.setInchiriere(inchiriere);
                    creantaService.insert(creanta);

                    Plata plata = new Plata();
                    plata.setDataPlata(new Date());
                    plata.setValoare(taxa.getValoare());
                    plata.setCreanta(creanta);
                    plataService.insert(plata);

                    setResponsePage(PiataViewPage.class);
                }
            };
            lkPlataRapida.add(new Label("lblPlataRapida", taxa.getDenumire()));

            li.add(lkPlataRapida);
        }

    }

}
